using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Text;
using System.IO;
using System.Windows.Forms;

namespace AddKeyMatches
{
    public partial class Form1 : Form
    {
        public Form1()
        {
            InitializeComponent();
            cbType.SelectedIndex = 0;
        }

        private void button1_Click(object sender, EventArgs e)
        {
            this.openFileDialog1.ShowDialog();
            FillGrid();
        }

        private void FillGrid()
        {
            StreamReader sr = new StreamReader(this.openFileDialog1.FileName);
            string l = "";
            this.dsKeyMatches1.KM.Clear();
            while ((l = sr.ReadLine()) != null)
            {
                // TODO how are commas handled in keymatch files
                String[] tokens = l.Split(',');
                if (tokens.Length < 4)
                {
                    continue;
                }
                else
                {
                    String keymatch = tokens[0];
                    String matchType = tokens[1];
                    String url = tokens[2];
                    String matchString = tokens[3];

                    this.dsKeyMatches1.KM.AddKMRow(keymatch, matchType, url, matchString);
                }
            }
            sr.Close();
        }

        private void button3_Click(object sender, EventArgs e)
        {
            this.dsKeyMatches1.KM.AddKMRow(txtKM.Text,cbType.Text, txtUrl.Text, txtMatchString.Text);
        }

        private void button2_Click(object sender, EventArgs e)
        {
            this.dsKeyMatches1.AcceptChanges();

            StreamWriter sw = new StreamWriter(this.openFileDialog1.FileName);
            sw.AutoFlush = true;
            foreach (dsKeyMatches.KMRow row in this.dsKeyMatches1.KM.Rows)
            {
                sw.WriteLine(row.keymatch + "," + row.matchType + "," + row.url + "," + row.matchString+ "");
            }

            sw.Close();
        }
    }
}